<template>
    <div id="cesiumContainer"></div>
  
    <div id="infoBox" style="display: flex; justify-content: space-around; font-size: 14px;">
        <p>鼠标经度: <span id="longitude">N/A</span></p>
        <p>鼠标纬度: <span id="latitude">N/A</span></p>
        <p>相机Heading: <span id="heading">N/A</span></p>
        <p>相机Pitch: <span id="pitch">N/A</span></p>
        <p>相机Roll: <span id="roll">N/A</span></p>
        <div>相机高度: <span id="cameraHeight">N/A</span></div>
    </div>

    <button id="customTopButton" @click="handleCustomButtonClick">自定义按钮</button>
    <div id="customDIV">
        <h3>模型加载</h3>
        <button @click="addModels">加载模型</button>
        <div></div>
        <h3>模型控制</h3>
        <button @click="removeModels">移除模型</button>
        <div></div>
    </div>
  
  </template>
  
  <script setup lang='ts'>
import * as Cesium from "cesium";
import { onMounted } from "vue";

import { CesiumViewer } from '../../scripts/cesiumConfig.ts';
import { tdtImageryLayer,gdImageryLayer,LocalTerrainServer } from '../../scripts/mapLoader.ts';

import { wuhanBaimo } from '../../scripts/3dtilesLoader.ts';

// 加载单个模型所需函数
import { LoadGLBFromURL } from '../../scripts/loadglb.ts';

// 批量加载模型所需函数
import { proj4548ToProj4326 } from '../../scripts/corrdinateProj.ts';
import {GetFileURL} from '../../scripts/ToolFunctions/getImgFromUrl.ts';
  
  
  let viewer:Cesium.Viewer;
  let scene:Cesium.Scene;
  
  onMounted(async () => {
  
  // NOTE:Cesium离线运行
  
  viewer = CesiumViewer("cesiumContainer");
  // console.log("viewer:",viewer);
  scene = viewer.scene;
  
  const infoBox = document.getElementById('infoBox');
  const longitudeSpan = document.getElementById('longitude');
  const latitudeSpan = document.getElementById('latitude');
  const headingSpan = document.getElementById('heading');
  const pitchSpan = document.getElementById('pitch');
  const rollSpan = document.getElementById('roll');
  const heightSpan = document.getElementById('cameraHeight');
  
  // 鼠标移动监听
  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction((movement) => {
    const cartesian = viewer.scene.pickPosition(movement.endPosition);
    if (cartesian) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
        const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
  
        longitudeSpan.innerText = longitude;
        latitudeSpan.innerText = latitude;
    } else {
        longitudeSpan.innerText = 'N/A';
        latitudeSpan.innerText = 'N/A';
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  
  // 相机变化监听
  viewer.scene.postRender.addEventListener(() => {
    const camera = viewer.camera;
  
    const heading = Cesium.Math.toDegrees(camera.heading).toFixed(2);
    const pitch = Cesium.Math.toDegrees(camera.pitch).toFixed(2);
    const roll = Cesium.Math.toDegrees(camera.roll).toFixed(2);
  
    headingSpan.innerText = heading;
    pitchSpan.innerText = pitch;
    rollSpan.innerText = roll;
  
    const cameraPosition = viewer.camera.positionCartographic;
    const cameraHeight = cameraPosition.height.toFixed(2); // 相机高度（米）
    // 在页面中显示相机高度
    heightSpan.innerText = cameraHeight;
    
  });


  // 设置相机视角位置
  const cameraLon = 113.955282;
  const cameraLat = 30.206550;
  const cameraHeight = 135000.0;
  const cameraPosition = Cesium.Cartesian3.fromDegrees(cameraLon, cameraLat, cameraHeight);
  
  // 设置相机视图
  viewer.camera.setView({
    destination: cameraPosition,
    orientation: {
        heading: Cesium.Math.toRadians(345),
        pitch: Cesium.Math.toRadians(-90),
        roll: 0
    }
  });
  
  
  // 在此处添加你自己的代码内容
//   console.log("-----------------");
//   console.log("viewer:",viewer);
//   console.log("scene is ",viewer.scene);

  
// 加载武汉切片地形数据
const localTerrainServerURL = ' http://127.0.0.1:8083/';//临时端口
viewer.scene.setTerrain(LocalTerrainServer(localTerrainServerURL));

// // 控制地形数据的请求频率和质量
// viewer.scene.globe.maximumScreenSpaceError = 0.2;

// 地形夸张
viewer.scene.globe.terrainExaggeration = 1.0;

// NOTE:避免某些情况下 viewer.entities 可能被地形遮挡
// viewer.scene.globe.depthTestAgainstTerrain = false;


// // 加载高德地图
// const imageryProvider = gdImageryLayer();
const imageryProvider = tdtImageryLayer();//天地图与白模位置匹配
viewer.imageryLayers.addImageryProvider(imageryProvider);

// 武汉市白模
const baimo = wuhanBaimo("http://127.0.0.1:8084/tileset.json");//临时端口
viewer.scene.primitives.add(baimo);

});

const originX = 432940.90625;
const originY = 3288375.0;
const lonlatPos = proj4548ToProj4326(originX,originY);
// console.log(`orogin point lonlatPos is lon:${lonlatPos[0]}, lat:${lonlatPos[1]}`);

//全局对象，存储当前加载显示的洪湖模型
let mesh:Cesium.Model = null;

let currentIndex = 0; // 当前显示的索引
let currentUrl = ""; // 当前显示的 URL

let switchInterval: number | undefined; // 定时器 ID

let fileUrls: string[] = []; // 确保fileUrls是一个数组类型

function handleCustomButtonClick() {
    console.log("自定义按钮被点击！");
}


async function addModels(){
    console.log("viewer is ",viewer);
    console.log("scene is ",viewer.scene);
    // TODO:

    // // INFO:加载单个模型
    // const glbUrl = 'http://localhost:8082/WQR/WQR_2023_12_1_0_0_0.glb';
    // let lakeMesh = await LoadGLBFromURL(glbUrl,viewer,lonlatPos[0],lonlatPos[1]);
    // console.log("lakeMesh:",lakeMesh);

    // INFO:加载多个模型并进行切换
    // 替换为自己的模型文件地址
    const temperatureUrl = "http://localhost:8082/WQR/";
    // 初始化图片加载
    await initializeIChanges(temperatureUrl);

}



async function initializeIChanges(baseUrl:string) {
    try {
        fileUrls = await GetFileURL(baseUrl,'.glb');
        // console.log("fileUrls:", fileUrls);

        if (fileUrls.length > 0) {
            // 初始化第一个文件
            currentUrl = fileUrls[currentIndex];
            // console.log("Switching to first image URL:", currentUrl);

            // 开始轮换
            startSwitching();
        } else {
            console.error("No images available for switching.");
        }
    } catch (error) {
        console.error("Error fetching images:", error);
    }
}

// 开始轮换
function startSwitching() {
    switchInterval = setInterval(SwitchModels, 1000); // 每 1 秒切换一次，可根据需求调整时间间隔
}

// 停止轮换
function stopSwitchingModels() {
    if (switchInterval !== undefined) {
        clearInterval(switchInterval);
        console.log('轮换已停止');
    }
}

// 切换
function SwitchModels() {
    currentIndex = (currentIndex + 1) % fileUrls.length;
    const newUrl = fileUrls[currentIndex];

    if(currentIndex == fileUrls.length - 1){
        stopSwitchingModels();
        // currentIndex = 0;

    }else{
        // 如果新旧URL不同，则更新
        if (newUrl !== currentUrl) {
            currentUrl = newUrl;
            console.log("Switching to new URL:", currentUrl);

            SwitchModelFromURL(currentUrl, viewer);
        }
    }
 
}

async function SwitchModelFromURL(url:string,viewer:Cesium.Viewer){
    if(mesh){
        viewer.scene.primitives.remove(mesh);
    
        // viewer.scene.primitives.removeAll();
    }
    
    // console.log("切换加载的模型");
    mesh = await LoadGLBFromURL(url,viewer,lonlatPos[0],lonlatPos[1]);
}

// 必须等模型加载完毕之后才可移除
function removeModels(){
    cosnole.log("移除模型");

    if(mesh){
        viewer.value.scene.primitives.remove(mesh);
    
        // viewer.scene.primitives.removeAll();
    }else{
        console.error("mesh is null");
    }
}
  
  
  
  
  
  

  
  </script>
  
  <style scoped>
  #cesiumContainer{ 
    width: 100%;
    height: 100vh; 
    padding: 0;
    margin: 0;
    overflow:
    hidden;
  }
  #infoBox{
    position: fixed; 
    bottom: 0; 
    left: 0; 
    width: 100%; 
    background: rgba(42, 42, 42, 0.8); 
    color: white; 
    padding: 10px; 
    border-top: 2px solid #fff; 
    font-family: Arial, sans-serif; 
    z-index: 1000; 
    box-sizing: border-box;
  }

  /* 新增按钮样式，确保其显示在Cesium视图上层右上角 */
#customDIV {
  position: fixed;
  top: 20px;
  right: 30px;
  z-index: 2000;
  padding: 10px 20px;
  background: #1976d2;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
#customDIV:hover {
  background: #1565c0;
}

#customTopButton {
  position: fixed;
  top: 20px;
  left: 30px;
  z-index: 2000;
  padding: 10px 20px;
  background: #1976d2;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
  </style>
  